import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Image;
import java.awt.List;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MyTrayIcon {

	/** Pre-initialized instance */
	private static MyTrayIcon INSTANCE = new MyTrayIcon();

	private static SendRoutine threadSend;
	
	private static Server threadServer;
	
	/** Sys tray icon to be changed */
	private static TrayIcon trayIcon = null;

	/** List of all icpns inside the sys tray */
	private static ArrayList<Image> icons = null;
	
	private static Image defaultImage = null;

	// ------------------------------------------------------
	// Save my work Item
	private static MenuItem saveItem;

	// ------------------------------------------------------
	// Save my work Item
	private static MenuItem backupItem;

	// ------------------------------------------------------
	// Preferences Item
	private static MenuItem preferences;

	// ------------------------------------------------------
	// About Item
	private static MenuItem about;

	// ------------------------------------------------------
	// Exit Item
	private static MenuItem exitItem;

	/** Private constructor */
	private MyTrayIcon() {
	}

	/** Access point for the singleton instance */
	public static MyTrayIcon getInstance() {
		return INSTANCE;
	}
	
	static SaveWorkRoutine swr = null;

	/** Displays the tray icon */
	public static void displayTray() {

		// Check the SystemTray is supported
		if (!SystemTray.isSupported()) {
			System.out.println("SystemTray is not supported");
			return;
		}

		// Create the popup menu
		final PopupMenu popup = new PopupMenu();

		// Create the icon list
		icons = new ArrayList<Image>();
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/default-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/add-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/error-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/network-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/playing-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/remove-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/transfer-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/validation-icon.png"));
		icons.add(Toolkit.getDefaultToolkit().getImage(
				"img/white-icon/wainting-icon.png"));

		defaultImage = icons.get(0);
		trayIcon = new TrayIcon(defaultImage);

		// Get the system tray
		final SystemTray tray = SystemTray.getSystemTray();

		// ------------------------------------------------------
		// Save my work Item
		saveItem = new MenuItem("Save my data");
		saveItem.setEnabled(false);
		saveItem.addActionListener( new ActionListener(){
	        public void actionPerformed(ActionEvent e){
	        	
	        	changeIconToAdd();
	            System.out.println("Save detected");
	            swr = new SaveWorkRoutine(new Callback(){
					@Override
					public void callback() {
						
						changeToCurrentDefaultImage();
						//PrefProperties.lastSave = (Date) Calendar.getInstance().getTime();
						System.out.println("Save finished");
						
						/* Here you have the file object from the working directory
						 * plus a parameter called "toSendPath" in which you can
						 * find the path leading to the ".crp" file you have to send. */
						ArrayList<FileObject> filesToSend = swr.getFilesToSend();
						for( FileObject fo : filesToSend ){
							System.out.println(fo.toSendPath);
						}
					}
	            });
	            Thread t1 = new Thread(swr);
	            t1.start();
	        }
	    });

		// ------------------------------------------------------
		// Data backup Item
		backupItem = new MenuItem("Get data backup");
		backupItem.setEnabled(false);
		backupItem.addActionListener( new ActionListener(){
	        public void actionPerformed(ActionEvent e){
	        	
	        	changeIconToTransfer();
	        	
	            System.out.println("Backup detected");
	            
	            if(!PrefProperties.demoMode){
	            	
	            	Client cl;
	            	InetAddress localhost;
	            	RecoverWorkRoutine rwr;
	            	Thread t;
	            	
	                for (int port = PrefProperties.inputPortMin; port <= PrefProperties.inputPortMax; port++)
	                {
		                	cl=new Client(new Callback(){
		 						@Override
		 						public void callback() {
		 							System.out.println("CLIENT - Back-up demand has been sent.");
		 							
		 						}}, new FileObject(PrefProperties.login ,1),"localhost",port);
		 					
		 					cl.run();
		               
		                
			                rwr = new RecoverWorkRoutine(new Callback(){
								@Override
								public void callback() {
									
									changeToCurrentDefaultImage();
									System.out.println("Get back-up ...");
								}
				            });

				            t = new Thread(rwr);
				            t.start();
	              }
	            }
	            
	        }
	    });

		// ------------------------------------------------------
		// Preferences Item
		preferences = new MenuItem("Open preferences ...");
		preferences.setEnabled(false);

		// ------------------------------------------------------
		// About Item
		about = new MenuItem("About ...");

		// ------------------------------------------------------
		// Exit Item
		exitItem = new MenuItem("Exit");
		exitItem.addActionListener(new exitApp());

		// Add components to pop-up men
		popup.add(saveItem);
		popup.add(backupItem);
		popup.addSeparator();
		popup.add(preferences);
		popup.add(about);
		popup.add(exitItem);

		trayIcon.setPopupMenu(popup);

		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			System.out.println("TrayIcon could not be added.");
		}
	}
	
	/* Enables the user to use the menu */
	public static void enableMenu(){
		saveItem.setEnabled(true);
		backupItem.setEnabled(true);
		preferences.setEnabled(true);
		about.setEnabled(true);
		exitItem.setEnabled(true);
	}
	
	public static void startServer() {

		// Create routine instance for sending file
		threadSend = new SendRoutine();
		threadSend.start();
		
		// Create server thread
		threadServer = new Server();
		threadServer.start();
	}

	private static void changeToCurrentDefaultImage() {
		trayIcon.setImage(defaultImage);
	}
	
	public static void changeIconToDefault() {
		trayIcon.setImage(icons.get(0));
		defaultImage = icons.get(0);
	}
	
	public static void changeIconToDefaultPlay() {
		trayIcon.setImage(icons.get(4));
		defaultImage = icons.get(4);
	}

	public static void changeIconToAdd() {
		trayIcon.setImage(icons.get(1));
	}

	public static void changeIconToError() {
		trayIcon.setImage(icons.get(2));
	}

	public static void changeIconToNetwork() {
		trayIcon.setImage(icons.get(3));
	}

	public static void changeIconToPlaying() {
		trayIcon.setImage(icons.get(4));
	}

	public static void changeIconToRemove() {
		trayIcon.setImage(icons.get(5));
	}

	public static void changeIconToTransfer() {
		trayIcon.setImage(icons.get(6));
	}

	public static void changeIconToValidation() {
		trayIcon.setImage(icons.get(7));
	}

	public static void changeIconToWaiting() {
		trayIcon.setImage(icons.get(8));
	}

	// Exit app
	static class exitApp implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			PrefProperties.savePreferences();
			System.exit(0);
		}
	}
}
